import React from 'react';
import { BrowserRouter as Router, Routes, Route, Navigate } from 'react-router-dom';
import { Provider } from 'react-redux';
import { ConfigProvider } from 'antd';
import zhCN from 'antd/locale/zh_CN';
import store from './store';
import Login from './pages/auth/Login';
import Register from './pages/auth/Register';
import { useSelector } from 'react-redux';
import MainLayout from './components/Layout';

// 路由保护组件
const PrivateRoute = ({ children }) => {
  const isAuthenticated = useSelector(state => state.user.isAuthenticated);
  const isAdmin = useSelector(state => state.user.currentUser?.role === 'admin');

  if (!isAuthenticated) {
    return <Navigate to="/login" />;
  }

  // 如果是管理员路由，检查用户是否是管理员
  if (children.props.requireAdmin && !isAdmin) {
    return <Navigate to="/" />;
  }

  return children;
};

const App = () => {
  return (
    <Provider store={store}>
      <ConfigProvider locale={zhCN}>
        <Router>
          <Routes>
            {/* 公开路由 */}
            <Route path="/login" element={<Login />} />
            <Route path="/register" element={<Register />} />

            {/* 受保护路由 */}
            <Route path="/*" element={
              <PrivateRoute>
                <MainLayout />
              </PrivateRoute>
            } />
          </Routes>
        </Router>
      </ConfigProvider>
    </Provider>
  );
};

export default App;